// 角色增删改查

const assert = require('http-assert')
const Role = require('../model/RoleModel')
exports.all = async (req, res) => {
  const list = await Role.find()
  res.json({
    code: 20000,
    message: '获取所有角色成功',
    data: {
      items: list,
      total: list.length
    }
  })
}

exports.update = async (req, res) => {
  const id = req.params.id
  assert(id, 200, { code: 20001, message: '角色id不存在' })

  const role = await Role.findById(id)
  assert(role, 200, { code: 20001, message: '角色不存在' })

  let { name, parent, desc } = req.body
  assert(name, 200, { code: 20001, message: '角色名称不能为空' })
  if (parent) {
    try {
      const parentRole = await Role.findById(parent)
      if (!parentRole) {
        parent = undefined
      }
    } catch (error) {
      parent = undefined
    }
  }
  const result = await Role.findByIdAndUpdate(
    id,
    { name, parent, desc },
    { lean: true, new: true }
  )
  res.json({
    code: 20000,
    message: '更新角色成功',
    data: result
  })
}

exports.create = async (req, res) => {
  let { name, parent, desc } = req.body
  assert(name, 400, { code: 20001, message: '角色名称不能为空' })
  let result = {}
  if (parent) {
    try {
      await Role.findOne({ _id: parent })
    } catch (error) {
      parent = undefined
    }
  }
  result = await Role.create({ name, parent, desc })

  res.json({
    code: 20000,
    message: '创建角色成功',
    data: result
  })
}

exports.remove = async (req, res) => {
  const id = req.params.id
  assert(id, 400, { code: 20001, message: '路径参数错误' })
  await Role.findByIdAndRemove(req.params.id, { rawResult: true })
  res.send({
    code: 20000,
    message: '删除角色成功'
  })
}

exports.assignMenuPerms = async (req, res) => {
  const { id, menuCheckedKeys, menuHalfCheckedKeys } = req.body
  const role = await Role.findById(id)
  let result = {}
  if (role) {
    role.menuCheckedKeys = menuCheckedKeys
    role.menuHalfCheckedKeys = menuHalfCheckedKeys
    result = await role.save()
  }
  res.json({
    code: 20000,
    message: '角色的分配菜单权限成功',
    data: result
  })
}

exports.assignApiPerms = async (req, res) => {
  const { id, apiCheckedKeys, apiHalfCheckedKeys } = req.body
  const role = await Role.findById(id)
  let result = {}
  if (role) {
    role.apiCheckedKeys = apiCheckedKeys
    role.apiHalfCheckedKeys = apiHalfCheckedKeys
    result = await role.save()
  }
  res.json({
    code: 20000,
    message: '角色的分配api权限成功',
    data: result
  })
}
